package com.summer.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.summer.common.R;
import com.summer.entity.User;
import com.summer.service.UserService;
import com.summer.utils.SMSUtils;
import com.summer.utils.ValidateCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户控制器")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     * @param user 获取请求电话
     * @param session 设置验证码，用于登录校验
     * @return 返回字符串信息
     */
    @PostMapping("/sendMsg")
    @ApiOperation(value = "发送验证码")
    @ApiImplicitParams(@ApiImplicitParam(name = "user", value = "用于获取请求电话", required = true))
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        log.info("发送验证码请求，请求手机号为：{}",user.getPhone());
        if (!StringUtils.isEmpty(user.getPhone())){
            //1. 获取随机生成的4位验证码
            Integer code = ValidateCodeUtils.generateValidateCode(4);
            log.info("验证码为：{}", code);
            //2. 调用api发送验证码
            //SMSUtils.sendMessage("瑞吉外卖","",phone,code.toString());
            //3. 将验证码存入session
            //session.setAttribute("code", code);
            //3. 将验证码存入redis
            redisTemplate.opsForValue().set(user.getPhone(), String.valueOf(code), 5L, TimeUnit.MINUTES);

            //4. 返回发送成功信息
            return R.success("验证码发送成功");
        }
        return R.error("短信发送失败");  // TODO 防止有人越过前端的不校验手机号
    }


    /**
     * 登录校验
     * @param map 获取用户手机号和验证码
     * @return 返回登录成功信息
     */
    @PostMapping("/login")
    public R<User> loginCheck(@RequestBody Map<String,String> map, HttpSession session){
        log.info("登录校验，user={}",map);
        //1. 判断验证码是否正确，不正确则返回错误信息，正确则删除验证码缓存
        //String trueCode = (String) session.getAttribute("code").toString();
        String trueCode = (String) redisTemplate.opsForValue().get(map.get("phone"));
        if (trueCode != null && !map.get("code").equals(trueCode)){  // TODO 注意空指针异常（null对象引用方法抛出）
            return R.error("验证码错误");
        }
        redisTemplate.delete(map.get("phone"));

        //2. 判断用户是否为第一次登录，是则注册
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone, map.get("phone"));
        User user = userService.getOne(lqw);
        if (user == null){
            user = new User();
            user.setPhone(map.get("phone"));
            userService.save(user);
        }

        //3. 设置session
        session.setAttribute("user", user.getId());

        //4. 不是则返回
        return R.success(user);
    }

    /**
     * 移动端用户退出
     * @param session session
     * @return
     */
    @PostMapping("/loginout")
    public R<String> loginOut(HttpSession session){
        log.info("移动端用户退出");
        session.removeAttribute("user");
        return R.success("退出成功！");
    }
}
